/*
 * Copyright (c) 2016 VUI(https://git.oschina.net/durcframework/vui) All rights reserved.
 */

;(function(){
	
var currentZindex = VUI.Config.Win.zIndex;

var SIZE_ENUM = {
	normal:0
	,max:1
	,min:2
}

var getZIndex = function() {
	return ++currentZindex;
}

// 任务栏管理器
var taskbar = new VUI.Taskbar(this);

/**
 * @ignore
 * @class
 */
VUI.Class('WinView',{
	init:function(cmp) {
		this._super(cmp);
		this.winContId = 'winId_' + cmp.id;
		this.hide();
		this.sizeState = SIZE_ENUM.normal;// 0正常,1最大化,2最小化
	}
	// @override
	,getRenderDom:function() {
		return document.body;
	}
	// @override
	,afterRender:function() {
		this.initPanel();
		
		if(this.opt('url')) {
			this.initRemoteContent(this.opt('url'));
		}else{
			this.initContent();
		}
	}
	,initRemoteContent:function(url) {
		this.frameId = 'winFrameId' + this.cmp.id;
		this.$frame = $('<iframe id="' + this.frameId + '" src="' + url + '" width="100%" frameborder="0"></iframe>');
		if(!this.opt('lazyLoad')) {
			this.$frame.attr('src',url);
		}
		
		this.resizeFrame();
		
		$('#' + this.winContId).append(this.$frame);
	}
	,resizeFrame:function() {
		var size = this.getSize();
		if(this.$frame) {
			this.$frame.width(size.width-20).height(size.height-10);
		}
	}
	,initContent:function() {
		this.$targetWin = $('#' + this.opt('contentId'));
		$('#' + this.winContId).append(this.$targetWin);
		this.$targetWin.show();
	}
	,initPanel:function() {
		this.setSize(this.opt('width'),this.opt('height'));
		
		var $panel = this.getWraper();
		if(this.opt('shadow')) {
			$panel.addClass('pui-shadow');
		}
		
		var $title = $panel.find('.pui-dialog-titlebar').eq(0);
		
		this.initDragable($panel,$title);
	}
	,initDragable:function($win,$title) {
		if(this.opt('draggable')) {
			Drag.regist($win,$title);
		}
	}
	,move:function(left,top) {
		this.getWraper().css({left:left + 'px',top:top + 'px'});
	}
	// 带动画效果
	,animateMove:function(left,top){
		this.getWraper().animate({left:left,top:top});
	}
	// @override
	,show:function() {
		this.showModal();
		
		this.addWinZindex();
		
		this._super();
		
		this.normal();
		
		this.center();
		
		if(this.$frame && this.opt('lazyLoad')) {
			this.$frame.attr('src',this.opt('url'));
			this.resizeFrame();
		}
	}
	
	// 最大化
	,max:function() {
		
		if(!this.canMaxToggle()) {
			return;
		}
		
		if(this.sizeState == SIZE_ENUM.normal) {
			this.saveNormalState();
			
			var $window = $(window);
					
			var windowWidth = $window.width();
			var windowHeight = $window.height();
			
			this.move(0,0);
			
			this.setSize(windowWidth-2,windowHeight-80);
			
			this.sizeState = SIZE_ENUM.max;
			
			this.resizeFrame();
		}else{
			this.normal();
		}
		
	}
	// 最小化
	,min:function() {
		if(this.sizeState != SIZE_ENUM.min) {
			this.saveBeforeState();
			
			this.getWin().width('auto').height('auto').trigger('disableDrag');
			
			this.getVisiable().hide();
			
			taskbar.add(this);
			
			this.sizeState = SIZE_ENUM.min;
			
		} else{
			taskbar.del(this);
			this.restore();
		}
	}
	,restore:function() {
		this.sizeState = this.beforeState;
		
		var size = this.beforeSize;
		
		this.animateMove(this.beforeOffset.left,this.beforeOffset.top);
		
		this.setSize(size.width,size.height);
		
		this.getVisiable().show();
		
		this.getWraper().trigger('enableDrag');
	}
	,normal:function() {
		this.sizeState = SIZE_ENUM.normal;
		var $win = this.getWraper();
		var size = this.normalSize;
		$win.offset(this.normalOffset);
		
		if(size) {
			this.setSize(size.width,size.height);
		}
		
		this.resizeFrame();
	}
	// 保存之前状态
	,saveBeforeState:function() {
		this.saveState();
		this.saveBeforeSize();
		this.saveBeforePos();
	}
	// 保存原始状态
	,saveNormalState:function() {
		var $win = this.getWin();
		this.normalSize = this.getSize();
		this.normalOffset = $win.offset();
	}
	,saveBeforeSize:function() {
		this.beforeSize = this.getSize();
	}
	,saveBeforePos:function() {
		var $win = this.getWin();
		
		this.beforeOffset = $win.offset();
	}
	,saveState:function() {
		this.beforeState = this.sizeState;
	}
	,isMaxState:function() {
		return this.sizeState == SIZE_ENUM.max;
	}
	,isMinState:function() {
		return this.sizeState == SIZE_ENUM.min;
	}
	,setSize:function(width,height) {
		var $win = this.getVisiable();
		if(width) {
			$win.width(width);
		}
		if(height) {
			$win.height(height);
		}
	}
	,getSize:function() {
		var $win = this.getVisiable();
		return {width:$win.width(),height:$win.height()};
	}
	,setWinZIndex:function(zIndex) {
		this.getWraper().css('z-index',zIndex)
	}
	,hide:function() {
		this._super();
		this.hideModal();
	}
	,showModal:function() {
		var $modal = this.getModal();
		
		if($modal) {
			var $doc = $(document);
			var $body = $('body');
				
			var clientHeight = $doc.height();
			var scrollHeight = $doc.scrollTop() || $body.scrollTop();
			
			var height = Math.max(clientHeight,scrollHeight);
			var zIndex = getZIndex();
			
			$modal.height(height).css('z-index',zIndex).show();
		}
	}
	,hideModal:function() {
		var $modal = this.getModal();
		
		if($modal) {
			$modal.hide();	
		}
	}
	,getModal:function() {
		if(this.opt('modal')) {
			if(!this.$modal){
				this.$modal = this.createModal();
				$('body').append(this.$modal);
			}
			return this.$modal;
		}
	}
	,panelClick:function(e) {
		var $target = $(e.target);
		var isClickSelf = 
		$target.hasClass('pui-dialog-titlebar') 
		 	|| $target.hasClass('pui-dialog-buttonpane') 
			|| $target.attr('id') == this.opt('contentId');
		
		if( isClickSelf ) {
			this.addWinZindex();
		}
	}
	,addWinZindex:function() {
		var zIndex = getZIndex();
		this.setWinZIndex(zIndex);
	}
	,createModal:function() {
		return $('<div class="ui-widget-overlay"></div>').css('z-index',this.modalZindex).hide();
	}
	// 居中
	,center:function() {
		if(this.sizeState == SIZE_ENUM.normal) {
			var $window = $(window);
			var $doc = $(document);
			var $body = $(document.body);
			
			var clientHeight = $window.height()
				,clientWidth = $window.width()
				,scrollLeft = $doc.scrollLeft() || $body.scrollLeft()
				,left = clientWidth * 0.35 + scrollLeft
				,top = clientHeight * 0.25;
			
			var $win = this.getWin();
			
			var winWidth = $win.width() || 200;
			var winHeight = $win.height() || 30;
			
			if(winWidth){
				left = (clientWidth*0.5 - (parseInt(winWidth))*0.5) - 10;
			}
			
			if(winHeight) {
				top = (clientHeight*0.5 - (parseInt(winHeight))*0.5) - 50;
			}
			
			this.move(left,top);
		}
	}
	,hideBtn:function(index) {
		this.getWin().find('.vui-win-btn').eq(index).hide();
	}
	,showBtn:function(index) {
		this.getWin().find('.vui-win-btn').eq(index).show();
	}
	,canMaxToggle:function() {
		return this.opt('maximizable') && this.sizeState != SIZE_ENUM.min;
	}
	,getWin:function() {
		if(!this._$win) {
			this._$win = this.getWraper().find('.pui-dialog');
		}
		return this._$win;
	}
	,getVisiable:function() {
		if(!this._$visi) {
			this._$visi = this.getWin().find('.aj-content').eq(0);
		}
		return this._$visi;
	}
	,getBtnPanel:function() {
		return this.getWin().find('.pui-dialog-buttonpane').eq(0);
	}
	,vBtnClick:function(btn,e) {
		btn.handler.call(this.cmp,{target:e.target});
	}
	,getTemplate:function(){
		var template = 
		'<div @click="cmp.view.panelClick($event)" style="position: static;" class="pui-dialog ui-widget ui-widget-content ui-corner-all">' +
			// title
			'<div @dblclick="cmp.max()" class="pui-dialog-titlebar ui-widget-header ui-helper-clearfix ui-corner-top" style="font-size: 12px;">' +
			    '<span class="pui-dialog-title" unselectable="on" onselectstart="return false;" style="-moz-user-select: none;">' +
			       	 '{{{cmp.opt(\'title\')}}}' +
			    '</span>' +
			    '<a v-if="cmp.opt(\'closable\')" @click="cmp.hide()" class="pui-dialog-titlebar-icon pui-dialog-titlebar-close ui-corner-all">' +
			        '<span class="ui-icon ui-icon-close"></span>' +
			    '</a>' +
			    '<a v-if="cmp.view.canMaxToggle()" @click="cmp.max()" class="pui-dialog-titlebar-icon pui-dialog-titlebar-maximize ui-corner-all">' +
			    	'<span :class="cmp.view.isMaxState()?\'ui-icon-newwin\':\'ui-icon-extlink\'" class="ui-icon"></span>' +
			    '</a>' +
			    '<a v-if="cmp.opt(\'minimizable\')" @click="cmp.min()" class="pui-dialog-titlebar-icon pui-dialog-titlebar-minimize ui-corner-all">' +
			    	'<span :class="cmp.view.isMinState() ? \'ui-icon-plus\': \'ui-icon-minus\'" class="ui-icon"></span>' +
			    '</a>' +
			'</div>' +
			'<div class="aj-content">' + 
				// content
				'<div class="pui-dialog-content ui-widget-content">' +
					'<div id="'+this.winContId+'"></div>' +
				'</div>' +
			'</div>' +
			// botton
			'<div v-show="cmp.hasBtns()" class="pui-dialog-buttonpane ui-widget-content ui-helper-clearfix">' +
				'<button type="button" v-for="btn in cmp.opts.buttons" @click="cmp.view.vBtnClick(btn,$event)" class="vui-win-btn pui-button ui-widget ui-state-default ui-corner-all pui-button-text-only">' +
					'<span class="pui-button-text">{{btn.text}}</span>' +
				'</button>' +
			'</div>' +
		'</div>' +
		'';
		return template;
	}
},VUI.View);

/**
 * 窗体拖拽工具类
 * @example 示例:
 * // 注册
 * Drag.regist($winDiv,$titleDiv);
 * @class
 */
var Drag = (function(){

	var clickedClientX = 0;
	var clickedClientY = 0;
	var oldTop = 0;
	var oldLeft = 0;
	var winHeight = 0;
	
	var $window = $(window);
	var $document = $(document);
	
	return {
		/**
		 * 注册拖拽
		 * 需要传入整个窗体dom和标题部分的dom
		 */
		regist:function($win,$title) {
			$title.css({cursor:'move'});
				
			$title.on('mousedown',function(evt) {
			    evt.preventDefault();
			    // 窗口尺寸
			    clientHeight = $window.height();
				clientWidth = $window.width();
			    
			    // 鼠标点击title时的位置
				clickedClientX = evt.clientX;
				clickedClientY = evt.clientY;
				
				var winOffset = $win.offset();
				
				// 窗体原始坐标,相对于窗体左上角
				oldTop = parseInt(winOffset.top);
				oldLeft = parseInt(winOffset.left);
				
			    $document.on('mousemove', mousemove);
			    $document.on('mouseup', mouseup);
			});
			
			function mousemove(e) {
			    // 水平拖行距离 = 鼠标滑动时的位置 - 鼠标点击title时的位置
				var dragSizeWidth = e.clientX - clickedClientX; // 水平拖动距离
				var dragSizeHeight = e.clientY - clickedClientY; // 垂直拖动距离
				// 窗体新的坐标 = 鼠标拖动距离 + 窗体老的坐标距离
				var newLeft = dragSizeWidth + oldLeft;							
				var newTop = dragSizeHeight + oldTop;
				
				if (newLeft < clientWidth) {
					$win.css({left: newLeft + "px"});
				}
				if(newTop > 0 && newTop < clientHeight - 30){
					$win.css({top: newTop + "px"});
				}
			}
			
			function mouseup() {
			    $document.off('mousemove', mousemove);
			    $document.off('mouseup', mouseup);
			}
			
			$win.bind('enableDrag',function() {
				Drag.regist($win,$title);
			});
			
			$win.bind('disableDrag',function() {
				Drag.destory($title);
			});
		}
		/**
		 * 注销,取消拖拽
		 */
		,destory:function($title) {
			$title.css({cursor:'default'});
			$title.unbind('mousedown');
		}
	}
})();

})();